/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.wms.web;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.infor.entity.Goods;
import com.jeeplus.modules.infor.service.GoodsService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.wms.entity.InoroutStatistics;
import com.jeeplus.modules.wms.service.InoroutStatisticsService;

/**
 * 出入库统计Controller
 * @author 李超辉
 * @version 2018-07-13
 */
@Controller
@RequestMapping(value = "${adminPath}/wms/inoroutStatistics")
public class InoroutStatisticsController extends BaseController {

	@Autowired
	private InoroutStatisticsService inoroutStatisticsService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private GoodsService goodsService;
	
	@ModelAttribute
	public InoroutStatistics get(@RequestParam(required=false) String id) {
		InoroutStatistics entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = inoroutStatisticsService.get(id);
		}
		if (entity == null){
			entity = new InoroutStatistics();
		}
		return entity;
	}
	
	/**
	 * 出入库统计列表页面
	 */
	@RequiresPermissions("wms:inoroutStatistics:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/wms/inoroutStatisticsList";
	}
	
		/**
	 * 出入库统计列表数据
	 */
	@ResponseBody
	@RequiresPermissions("wms:inoroutStatistics:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(InoroutStatistics inoroutStatistics, HttpServletRequest request, HttpServletResponse response, Model model) {
	     String pro=UserUtils.getUseroffice();
	     if(!pro.equals("总部")){
	     	inoroutStatistics.setPro(pro);
		 }
			Page<InoroutStatistics> page = inoroutStatisticsService.findPage(new Page<InoroutStatistics>(request, response), inoroutStatistics);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑出入库统计表单页面
	 */
	@RequiresPermissions(value={"wms:inoroutStatistics:view","wms:inoroutStatistics:add","wms:inoroutStatistics:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(InoroutStatistics inoroutStatistics, Model model) {
		model.addAttribute("inoroutStatistics", inoroutStatistics);
		return "modules/wms/inoroutStatisticsForm";
	}

	/**
	 * 保存出入库统计
	 */
	@ResponseBody
	@RequiresPermissions(value={"wms:inoroutStatistics:add","wms:inoroutStatistics:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(InoroutStatistics inoroutStatistics, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, inoroutStatistics)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		inoroutStatisticsService.save(inoroutStatistics);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存出入库统计成功");
		return j;
	}
	
	/**
	 * 删除出入库统计
	 */
	@ResponseBody
	@RequiresPermissions("wms:inoroutStatistics:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(InoroutStatistics inoroutStatistics, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		inoroutStatisticsService.delete(inoroutStatistics);
		j.setMsg("删除出入库统计成功");
		return j;
	}
	
	/**
	 * 批量删除出入库统计
	 */
	@ResponseBody
	@RequiresPermissions("wms:inoroutStatistics:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			inoroutStatisticsService.delete(inoroutStatisticsService.get(id));
		}
		j.setMsg("删除出入库统计成功");
		return j;
	}
	@ResponseBody
	@RequestMapping(value="cx")
	public String cx(String min,String max,String pro){
		if(min==""&max==""){
			return "";
		}
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			cha(min,max,pro);
		}else{
			cha(min,max, UserUtils.getUseroffice());
		}
		return "";
	}

	public void cha(String min,String max,String pro){
		String sql;
		String sq;
		String s;
		if(!pro.equals("总部")){
		s="delete from wms_inorout_statistics where pro='"+pro+"'"	;
		sql="SELECT p.project_name AS pro, p.code as code, p.name AS name, p.unit as unit,SUM(p.amount) as amount,p.work_type as type FROM wms_pickdetailed p  where to_days(p.create_date)>= to_days('"+min+"') and to_days(p.create_date)< to_days('"+max+"') and p.project_name='"+pro+"' GROUP BY p.project_name, p.`code`,p.work_type";
		sq="SELECT p.project_name AS pro, p.material_coding as code,SUM(p.quantities_received) as amount ,p.work_type as type FROM wms_receivings_notes p  where to_days(p.create_date)>= to_days('"+min+"') and to_days(p.create_date)< to_days('"+max+"') and p.project_name='"+pro+"' GROUP BY p.project_name, p.material_coding,p.work_type";
		}
		else{
			s="delete from wms_inorout_statistics "	;
			sql="SELECT p.project_name AS pro, p.code as code, p.name AS name, p.unit as unit,SUM(p.amount) as amount,p.work_type as type FROM wms_pickdetailed p  where to_days(p.create_date)>= to_days('"+min+"') and to_days(p.create_date)< to_days('"+max+"')  GROUP BY p.project_name, p.`code`,p.work_type";
			sq="SELECT p.project_name AS pro, p.material_coding as code,SUM(p.quantities_received) as amount ,p.work_type as type FROM wms_receivings_notes p  where to_days(p.create_date)>= to_days('"+min+"') and to_days(p.create_date)< to_days('"+max+"') GROUP BY p.project_name, p.material_coding,p.work_type";
		}
		jdbc.execute(s);
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		List<Map<String,Object>> maps=hb(list,lis);
		for(Map<String,Object> m:maps){
			InoroutStatistics i=new InoroutStatistics();
			i.setPro(m.get("pro")+"");
			i.setCode(m.get("code")+"");
			i.setName(m.get("name")+"");
			i.setType(m.get("type")+"");
			i.setJnum(m.get("amount")+"");
			i.setJweight(m.get("pweight")+"");
			i.setSnum(m.get("recive")+"");
			i.setSweight(m.get("rweight")+"");
			inoroutStatisticsService.save(i);
		}
	}
	public  List<Map<String ,Object>> hb(List<Map<String ,Object>> list,List<Map<String ,Object>> lis){
		NumberFormat nf = NumberFormat.getInstance();
		for(Map<String,Object> m:list){
			boolean bo=false;
			Goods goods=new Goods();
			goods.setProject(m.get("pro").toString());
			goods.setCode(m.get("code").toString());
			goods=goodsService.findList(goods).get(0);
			Double w=Double.parseDouble(goods.getGrossWeight());
			Double num= (Double) m.get("amount");
			m.put("pweight",nf.format(w*num));
			m.put("amount",num.toString().substring(0,num.toString().lastIndexOf(".")));
			for(Map<String,Object> map:lis){
				if(m.get("code").toString().equals(map.get("code").toString())&&m.get("type").toString().equals(map.get("type").toString())&&m.get("pro").toString().equals(map.get("pro").toString())){
					bo=true;
				}}
			if(bo){
				for(Map<String,Object> map:lis){
					if(m.get("code").toString().equals(map.get("code").toString())&&m.get("type").toString().equals(map.get("type").toString())&&m.get("pro").toString().equals(map.get("pro").toString())){
						Double p= (Double) map.get("amount");
						m.put("recive",p.toString().substring(0,p.toString().lastIndexOf(".")));
						m.put("rweight",nf.format(w*p));
					}
				}
			}else{
				m.put("recive","0");
				m.put("rweight","0");
			}


		}
		List<Map<String ,Object>> list11=new ArrayList<>();
		for(Map<String,Object> m:lis){
			boolean bol=true;
			for(Map<String,Object> mm:list){
				if(m.get("code").toString().equals(mm.get("code").toString())&&m.get("type").toString().equals(mm.get("type").toString())&&m.get("pro").toString().equals(mm.get("pro").toString())){
					bol=false;
					break;
				}
			}
			if(bol){
				Goods goods=new Goods();
				goods.setProject(m.get("pro").toString());
				goods.setCode(m.get("code").toString());
				goods=goodsService.findList(goods).get(0);
				Map<String,Object> mm=new HashMap<String, Object>() ;
				mm.put("name",goods.getName());
				mm.put("code",m.get("code"));
				mm.put("pro",m.get("pro"));
				mm.put("type",m.get("type"));
				mm.put("amount",0);
				mm.put("pweight",0);
				mm.put("recive",m.get("amount").toString().substring(0,m.get("amount").toString().lastIndexOf(".")));
				Double w=Double.parseDouble(goods.getGrossWeight());
				Double num= (Double) m.get("amount");
				mm.put("rweight",nf.format(w*num));
				list11.add(mm);
			}
		}
		list.addAll(list11);
		return  list;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("wms:inoroutStatistics:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(InoroutStatistics inoroutStatistics, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "出入库统计"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<InoroutStatistics> page = inoroutStatisticsService.findPage(new Page<InoroutStatistics>(request, response, -1), inoroutStatistics);
    		new ExportExcel("出入库统计", InoroutStatistics.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出出入库统计记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("wms:inoroutStatistics:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<InoroutStatistics> list = ei.getDataList(InoroutStatistics.class);
			for (InoroutStatistics inoroutStatistics : list){
				try{
					inoroutStatisticsService.save(inoroutStatistics);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条出入库统计记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条出入库统计记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入出入库统计失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/wms/inoroutStatistics/?repage";
    }
	
	/**
	 * 下载导入出入库统计数据模板
	 */
	@RequiresPermissions("wms:inoroutStatistics:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "出入库统计数据导入模板.xlsx";
    		List<InoroutStatistics> list = Lists.newArrayList(); 
    		new ExportExcel("出入库统计数据", InoroutStatistics.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/wms/inoroutStatistics/?repage";
    }

}